Page({
    data: {
        totalMoney: 0,
        totalNum: 0,
        cartList: []
    },
    onLoad: function (options) {},
    onShow() {
        let cartList = wx.getStorageSync('cart') || []
        this.setData({
            cartList: cartList
        })
        this.getTotal()
    },
    // 减少
    jian(e) {
        let id = e.currentTarget.dataset.id
        let cartList = this.data.cartList
        cartList.forEach(item => {
            if (item._id == id) {
                if (item.num > 0) {
                    item.num -= 1
                    if (item.num == 0) {
                        cartList.splice(index, 1)
                    }
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '数量不能小于0',
                    })
                }
            }
        })
        this.setData({
            cartList
        })
        this.getTotal()
        wx.setStorageSync('cart', cartList)
    },
    // 加
    jia(e) {
        let id = e.currentTarget.dataset.id
        let cartList = this.data.cartList
        cartList.forEach(item => {
            if (item._id == id) {
                item.num += 1
                if (cartList && cartList.length > 0) {
                    var result = cartList.find(cart => {
                        return cart._id == id
                    })
                    if (result) {
                        result.num = item.num
                    } else {
                        cartList.push(item)
                    }
                } else {
                    cartList.push(item)
                }
            }
        })
        this.setData({
            cartList
        })
        this.getTotal()
        wx.setStorageSync('cart', cartList)
    },
    // 计算总价格和总数量
    getTotal() {
        let cartList = this.data.cartList
        let totalMoney = 0
        let totalNum = 0
        cartList.forEach(item => {
            totalNum += item.num
            totalMoney += item.num * item.price
        })
        this.setData({
            totalNum,
            totalMoney
        })
    },
    // 删除购物车单条数据
    closeCartItem(e) {
        console.log(e.currentTarget.dataset.index)
        let index = e.currentTarget.dataset.index
        let cartList = this.data.cartList
        // 从购物车数组里删除当前菜品
        cartList.splice(index, 1)
        this.setData({
            cartList
        })
        // 重新计算总价格
        this.getTotal()
        // 把更新后的数据重新缓存
        wx.setStorageSync('cart', cartList)
    },
    goFood() {
        wx.navigateTo({
          url: '/pages/food/food',
        })
    },
    goPay() {
        wx.navigateTo({
          url: '/pages/pay/pay',
        })
    }
})